import java.util.Comparator;
import java.util.PriorityQueue;

//比较器
class IntCmp implements Comparator<Integer>{

    @Override
    public int compare(Integer o1, Integer o2) {
        return o2.compareTo(o1);
    }
}

public class test2 {


    //前k个最小的数  力扣
    public int[] minLestk(int[] arr, int k) {
        int[] ret = new int[k];
        if (arr == null || k <= 0) {
            return ret;
        }
        //1.创建一个数量为k的大根堆
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(new IntCmp());
        for (int i = 0; i < k; i++) {
            priorityQueue.offer(arr[i]);

        }
        //2.剩下元素逐个与堆顶比较
        for (int i = k; i < arr.length; i++) {
            //2.1比堆顶大的出堆顶，把另外的元素offer进来
            if (priorityQueue.peek()>arr[i]){
                priorityQueue.poll();
                priorityQueue.offer(arr[i]);
            }
        }
        for (int i=0;i<k;i++){
            ret[i]= priorityQueue.poll();
        }
        return ret;
    }


    //前k个最大的数
    public int[] maxLestk(int[] arr, int k) {
        int[] ret = new int[k];
        if (arr == null || k <= 0) {
            return ret;
        }
        //1.创建一个数量为k的小根堆
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
        for (int i = 0; i < k; i++) {
            priorityQueue.offer(arr[i]);

        }
        //2.剩下元素逐个与堆顶比较
        for (int i = k; i < arr.length; i++) {
            //2.1比堆顶大的出堆顶，把另外的元素offer进来
            if (priorityQueue.peek()<arr[i]){
                priorityQueue.poll();
                priorityQueue.offer(arr[i]);
            }
        }
        for (int i=0;i<k;i++){
            ret[i]= priorityQueue.poll();
        }
        return ret;
    }

    public static void main(String[] args) {

    }
}
